<template>
  <div>
    <div ref="svgContainer" class="svg-container"></div>
    <button @click="loadSVG">加载SVG文件</button>
    <input type="file" ref="fileInput" @change="handleFileChange" style="display: none;" />
    <button @click="undo">撤销</button>
    <button @click="redo">重绘</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { SVG, register } from '@svgdotjs/svg.js';

const svgContainer = ref(null);
const fileInput = ref(null);
const draw = ref(null);
const polygons = ref([]);
const history = ref([]);
let currentPolygon = [];
let isDragging = false;
let selectedPolygon = null;

onMounted(() => {
  draw.value = SVG().addTo(svgContainer.value).size('100%', '100%');
  draw.value.on('click', (event) => {
    if (selectedPolygon) {
      selectedPolygon.off('mousedown');
      selectedPolygon = null;
    }
    const point = event.point;
    currentPolygon.push(point);
    if (currentPolygon.length > 1) {
      draw.value.polyline(currentPolygon).fill('none').stroke({ color: '#000', width: 2 });
    }
    if (currentPolygon.length > 2 && point.distance(currentPolygon[0]) < 5) {
      const polygon = draw.value.polygon(currentPolygon).fill('#f00').stroke({ color: '#000', width: 2 });
      polygon.on('mousedown', () => {
        isDragging = true;
        selectedPolygon = polygon;
      });
      document.addEventListener('mouseup', () => {
        isDragging = false;
      });
      document.addEventListener('mousemove', (e) => {
        if (isDragging && selectedPolygon) {
          const delta = e.movementX + ' ' + e.movementY;
          selectedPolygon.transform({ translate: delta });
        }
      });
      polygons.value.push(polygon);
      history.value.push([...polygons.value]);
      currentPolygon = [];
    }
  });
});

const loadSVG = () => {
  fileInput.value.click();
};

const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      const content = e.target.result;
      draw.value.clear();
      draw.value.svg(content);
    };
    reader.readAsText(file);
  }
};

const undo = () => {
  if (history.value.length > 1) {
    history.value.pop();
    const lastState = history.value[history.value.length - 1];
    draw.value.clear();
    lastState.forEach((polygon) => {
      draw.value.polygon(polygon.array()).fill('#f00').stroke({ color: '#000', width: 2 });
    });
  }
};

const redo = () => {
  // 重绘功能可以根据具体需求实现
  console.log('重绘功能待实现');
};
</script>

<style scoped>
.svg-container {
  width: 100%;
  height: 600px;
  border: 1px solid #ccc;
}
</style>